<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ page import="com.hp.hpl.jena.rdf.model.Model" %>
<%@ page import="com.hp.hpl.jena.query.QueryExecution" %>
<%@ page import="com.hp.hpl.jena.query.QuerySolution" %>
<%@ page import="com.hp.hpl.jena.query.ResultSet" %>
<%@ page import="java.util.List" %>
<%@ page import="jenajdo.JenaJDOFactory" %>
<%@ page import="thanantic.ThananticUtil" %>

<html>
<head>
	<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
	<script type="text/javascript">function checkQuery() {
		if (document.getElementById("queryText").value == "") {
			var queryError = document.getElementById("queryError").innerHTML = "Please Enter a query!";
			return false;
		}
		return true;
	}</script>
</head>
<body>
	<%
		String queryStr = request.getParameter("queryText");
		Model model = null;
		QueryExecution qExec = null;
		String errorMessage = "";
		if (queryStr == null)
			queryStr = "select * { ?subject ?predicate ?object }";
		else {
			model = JenaJDOFactory.createModelJDO();
			try {
				qExec = ThananticUtil.runQuery(model, queryStr);
			} catch (Exception ex) {
				errorMessage = ex.getMessage();
			}
		}
	%>
	<h1>Querier</h1>
	<div class="errorText" id="queryError"><%= errorMessage %></div>
	<form action="/query.jsp" method="get" onSubmit="return checkQuery()">
		<textarea id="queryText" name="queryText"><%= queryStr %></textarea>
		<input type="submit" value="Run Query" />
	</form>
	<%
		if (qExec != null) {
			ResultSet results = qExec.execSelect();
			if (results != null) {
				List<String> resVars = results.getResultVars();
	%>
		<table>
			<tr><% for (String resVar : resVars) { %>
				<th><%= resVar %></th>
			<% } %></tr>
		<%
			while (results.hasNext()) {
				QuerySolution soln = results.next();
		%>
			<tr><% for (String resVar : resVars) { %>
				<td><%= soln.get(resVar).toString() %></td>
			<% } %></tr>
		<% } %></table>
	<%
			}
			qExec.close();
			model.close();
		}
	%>
</body>
</html>
